package mk.edu.ii.traval;

import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;

import android.widget.Button;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.location.Geocoder;


import java.util.*;

import android.location.Address;



public class AndroidLBS extends Activity {
    /** Called when the activity is first created. */
	 
	 private LocationManager myManager;
	 public Double lat=1000.0000000000;
	 public Double lon=1000.0000000000;
	 private String name;
	 
	//execute when the Activity is creating
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        //get reference to EditText view for input the name of the location
        final EditText nameLocation=(EditText) findViewById(R.id.EditText01);
                
        //get reference to Location Manager and Location Provider
        myManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
                
        // if we have Intent from MayMapActivity 
        // we get the information from it        
        Intent startedFrom = this.getIntent();
        lat = new Double(startedFrom.getDoubleExtra ("latitude",1000d));
        lon = new Double(startedFrom.getDoubleExtra ("longitude",1000d));
        name = ReverseGeoCoding(lat, lon);
                
        if (lat.doubleValue() != 1000 && lon.doubleValue() != 1000)
        {	
   	   	  	updateInformation(nameLocation);   	   	  		
        }
        
        //********************************************************************************
        
        //get reference to MyLocation Button and setting OnClick Listener
        final Button gpsButton = (Button) findViewById(R.id.gpsButton);
        gpsButton.setOnClickListener(new Button.OnClickListener(){
        public void onClick(View v){
        	//update information with my location
        	try{
        		Criteria criteria = new Criteria();
        		criteria.setAccuracy(Criteria.ACCURACY_FINE);
        		criteria.setAltitudeRequired(false);
        		criteria.setBearingRequired(false);
        		criteria.setCostAllowed(true);
        		criteria.setPowerRequirement(Criteria.POWER_LOW);
        		LocationManager locationManager=(LocationManager) getSystemService(Context.LOCATION_SERVICE);
        		String provider = locationManager.getBestProvider(criteria, true);
        	Location location =myManager.getLastKnownLocation(provider);
        	lat=location.getLatitude();
        	lon=location.getLongitude();
        	name=ReverseGeoCoding(lat, lon);
            updateInformation(nameLocation);
        	}
            catch (Exception e) {alertDialog(v,"Your location can not be determined!");} 
        }});
        
        //get reference to MAP VIEW and setting OnClick Listener
        final Button switchButton = (Button) findViewById(R.id.mapActivityButton);
		switchButton.setOnClickListener(new Button.OnClickListener() {
		public void onClick(View v){
			//initiate Intent to start MyMapActivity
		    Intent autocomplete = new Intent(v.getContext(),MyMapActivity.class);
	    	startActivity(autocomplete);
	    	
		}});
		
		//get reference to DONE Button and setting OnClick Listener
		final Button doneButton = (Button) findViewById(R.id.Button01);
		
		doneButton.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v){
				// initiate Intent to start LocationListActivity
				// and attach information on it
				if(!nameLocation.getText().toString().equals("")){
	            Intent sendBackLocation = new Intent(v.getContext(),LocationListActivity.class);
	            sendBackLocation.putExtra("latitude", lat);
	            sendBackLocation.putExtra("longitude", lon);
	            sendBackLocation.putExtra("location",nameLocation.getText().toString()); 
	            startActivity(sendBackLocation);
				}
				else{
					alertDialog(v,"You need to write name of the location");
				}
			}});
		
	
    }
    
    //update information in Information Area
    public void updateInformation(EditText nameLocation){
    		TextView latText = (TextView) findViewById(R.id.latText);
  	  		TextView lngText = (TextView) findViewById(R.id.lngText);
  	  		TextView location =(TextView) findViewById(R.id.Location);
  	  		
        
  	  		latText.setText(lat.toString());
  	  		lngText.setText(lon.toString());
  	  		location.setText(name);
  	  		nameLocation.setText(name);
    }
    
    //fire Alert Dialog if the Name of loaction is empty
    public void alertDialog(View v, String message){
    	Context context =v.getContext();
    	String title = "Warning";
    	
    	String button1String = "OK";
    	AlertDialog.Builder ad = new AlertDialog.Builder(context);
    	ad.setTitle(title);
    	ad.setMessage(message);
    	ad.setPositiveButton(button1String,new OnClickListener() {
    		public void onClick(DialogInterface dialog,int arg1) {
    		}
    	});
    	ad.show();
    }
    
	// functiont that return the Name of location
    // determined with latitude and longitude 
    private String ReverseGeoCoding(Double latitude,Double longitude)
    {
    	Geocoder gc = new Geocoder(getApplicationContext(), Locale.getDefault());
   	    
    	try {
    		List<Address> addresses = gc.getFromLocation(latitude, longitude, 1);
    		StringBuilder sb = new StringBuilder();
   			if (addresses.size() > 0) {
   				Address address = addresses.get(0);
   		        sb.append(address.getAddressLine(0));
   			    return sb.toString();
   			} 
   			else {
   				return "No location found";
   			}
   	    }
        catch (Exception e) {return "No location found";} 
    }
} 
      
